<template>
	<div class="page-container padding-20 query-list-container">
		<div v-show="$route.name === 'userMgt'">
			<div class="search-container">
				<el-form :inline="true" ref="form" :model="searchData" size="small">
					<el-form-item label="账号">
						<el-input v-model="searchData.loginName"></el-input>
					</el-form-item>
					<el-form-item label="角色">
						<el-select v-model="searchData.roleId" clearable>
							<el-option v-for="role in roleList" :key="role.id" :value="role.id" :label="role.name"></el-option>
						</el-select>
					</el-form-item>
					<el-button type="primary" @click="onSearch" size="small">查询</el-button>
					<el-button @click="onReset" size="small">重置</el-button>
				</el-form>
			</div>
			<div class="toolbar-container">
				<el-button type="primary" icon="el-icon-plus" size="small" @click="linkToAdd">新建</el-button>
			</div>
			<el-table class="mt-20 el-table-modify" :data="tableData" border>
				<el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
				<el-table-column prop="accountName" align="center" label="账号"></el-table-column>
				<el-table-column prop="name" align="center" label="员工姓名"></el-table-column>
				<el-table-column prop="roleName" align="center" label="角色"></el-table-column>
				<el-table-column prop="createdAt" align="center" label="创建时间">
					<template slot-scope="scope">
						<span>{{ scope.row.createdAt | dateFrm }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="lastLogin" align="center" label="最近登录时间">
					<template slot-scope="scope">
						<span>{{ scope.row.lastLogin | dateFrm }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" fixed="right" width="170">
					<template slot-scope="scope">
						<el-button size="mini" type="text" @click="linkToEdit(scope.row)">修改</el-button>
						<el-button v-if="scope.row.disable" size="mini" type="text" @click="enable(scope.row)">启用</el-button>
						<el-button v-else size="mini" type="text" @click="disable(scope.row)">禁用</el-button>
						<el-button size="mini" type="text" @click="resetPassword(scope.row)">重置密码</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				ref="pagination"
				class="mt-20"
				background
        :page-size.sync="pageOption.pageSize"
				:total="pageOption.total"
				@size-change="onSizeChange"
				@current-change="onPageChange"
				layout="slot,->,prev,pager,next,sizes,jumper"
			>
				<span class="pagination-title">
					共 {{ pageOption.total }} 条记录 第 {{ pageOption.page}} /
					{{ pageOption.pageTotal }} 页
				</span>
			</el-pagination>
		</div>
		<router-view
			v-if="$route.name !== 'userMgt'"
			@refresh="requestData"
			:roleList="roleList"
		></router-view>
	</div>
</template>

<script>
import { roleAll } from "@/api/roles";
import { userQuery, resetPassword, disableUser, enableUser } from "@/api/user";

export default {
  name: "UserMgt",
  data() {
    const {query} = this.$route
    let roleId = ""
    if (query && query.roleId) {
      roleId = query.roleId
    }

    return {
      searchData: {
        loginName: "",
        roleId
      },
      roleList: [],
      tableData: [],
      pageOption: {
        page: 1,
        pageSize: 20,
        total: 0,
        pageTotal: 1
      },
      selectData: null
    };
  },
  methods: {
    onSearch() {
      this.pageOption.page = 1;
      this.requestData();
    },
    onReset() {
      this.pageOption.page = 1;
      this.searchData.loginName = '';
      this.searchData.roleId = '';
      this.requestData();
    },
    linkToAdd() {
      this.$router.push({ name: "addUser" });
    },
    linkToEdit(row) {
      this.$router.push({ name: "editUser", params: {id: row.accountId}});
    },
    async enable(row) {
      try {
        this.$confirm('确定要启用该用户吗？', {
          type: 'warning',
          callback: async (action) => {
            if (action == 'confirm') {
              await enableUser(row.accountId);
              this.requestData();
            }
          }
        });
      } catch (err) {}
    },
    async disable(row) {
      try {
        this.$confirm('确定要禁用该用户吗？', {
          type: 'warning',
          callback: async (action) => {
            if (action == 'confirm') {
              await disableUser(row.accountId);
              this.requestData(); 
            }
          }
        });
      } catch (err) {}
    },
    async resetPassword(row) {
      this.$confirm('重置密码后，账户密码将变更为：123456，是否继续执行此操作？', {
        type: 'warning',
        callback: async (action) => {
          if (action == 'confirm') {
            await resetPassword(row.accountId)
            this.$message.success('重置密码成功') 
          }
        }
      });
    },
    async requestRole() {
      try {
        const { data } = await roleAll();
        this.roleList = data;
        const {query} = this.$routek
        if (query && query.roleId) {
          let role = data.find(item => item.id == query.roleId)
          this.searchData.roleId = role.name
        }
      } catch (err) {
        console.log(err);
      }
    },
    async requestData() {
      const { page, pageSize: size } = this.pageOption;
      const postData = {},
        searchData = this.searchData;
      Object.keys(searchData).forEach(item => {
        if (searchData[item]) {
          postData[item] = searchData[item];
        }
      });

      const { data, total } = await userQuery({ page: page - 1, size, ...postData });
      this.tableData = data;
      this.pageOption.total = total;
      this.pageOption.pageTotal = total ? Math.ceil(total / size) : 1;

      if (this.$refs.pagination) {
        let childrenRefs = this.$refs.pagination.$children;
        this.$nextTick(() => {
          childrenRefs.forEach(child => child.$forceUpdate());
        });
      }
    },
    onSizeChange(size) {
      this.pageOption.pageSize = size;
      this.requestData();
    },
    onPageChange(page) {
      this.pageOption.page = page;
      this.requestData();
    }
  },
  created() {
    const {query} = this.$route
    this.requestData();
    this.requestRole();
  }
};
</script>

<style lang="scss">
.pagination-title {
	font-weight: normal;
}
</style>
